package cqut.wys.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * TextSocketHandler处理类，TextWebSocketHandler是
 * 是对WebSocketHandler更进一层的封装和实现
 * @author wuyoushan@zbj.com
 * @date 2017/3/20.
 */
@Component
public class TextSocketHandler extends TextWebSocketHandler {

    /**返回线程安全集合*/
    private static final List<WebSocketSession> user= Collections.synchronizedList(new ArrayList<WebSocketSession>());
    /**
     * 连接成功时候
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception       {
        user.add(session);
        //处理离线消息
        session.sendMessage(new TextMessage("连接接webSocket成功TextSocket实现"));
    }

    //抛出异常时处理
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        //输出错误异常信息
        exception.printStackTrace();
    }

    //处理信息
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        super.handleBinaryMessage(session, message);
        String msg=message.getPayload().toString();
        String id=session.getId();
        Map<String,Object> map=session.getAttributes();
        String userName=map.get("user").toString();
        System.out.printf("收到ID为:%s\t用户名为:%s\t发送的消息\t%s",id,userName,message);
        System.out.println();
    }

    /**
     * 连接关闭时候
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    }

    /**
     * 发送消息
     * @param textMessage
     * @throws IOException
     */
    public void sendTextMessage(TextMessage textMessage){
        for (WebSocketSession session:user) {
            try {
                session.sendMessage(textMessage);
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }
}
